#include "FKVisualInterface.h"

#include "FKVisualInterfaceView.h"

#include <QQmlEngine>
#include <QQuickItem>
#include <QQmlContext>
#include <QKeyEvent>
#include <QCoreApplication>

#include "FKLogger.h"

FKVisualInterface::FKVisualInterface(QObject* parent):QObject(parent),_inited(false){
    FK_CBEGIN
    _view=0;
    FK_CEND
}

FKVisualInterface::~FKVisualInterface(){
    FK_DBEGIN
    if(_view)_view->deleteLater();
    FK_DEND
}

void FKVisualInterface::setView(FKVisualInterfaceView* v){
    if(_view){
        FK_MLOGV("view already exist. class:",this->metaObject()->className())
        return;
    }
    _view=v;
}

void FKVisualInterface::initialize(QWindow *parent){
//    FK_MLOG("initialization visual interface request")
    if(!_inited){
//        FK_MLOG("initialization visual interface pass")
        setView(initialization(parent));
        setupContextProperties(_view->rootContext());
        _view->loadFromqrc(_view->sourceFile());
        setupDefaults();
        if(parent){
            connect(parent,SIGNAL(activeChanged()),_view,SLOT(requestActivate()));
            _view->resize(parent->size());
        }
        _inited=true;
    }
}

void FKVisualInterface::setupDefaults(){
    connect(_view->engine(),SIGNAL(quit()),qApp,SLOT(quit()));
    connect(_view->rootObject(),SIGNAL(ok()),SIGNAL(ok()));
    connect(_view->rootObject(),FKQmlSignal2(virtualKeyPressed),FKQmlSlot2(virtualKeyPressed));
    connect(this,FKQmlSignal1(messageRequested),_view->rootObject(),FKQmlSignal1(eMessage));
}

void FKVisualInterface::show(){
    if(_view){
        _view->showMaximized();
        _view->requestActivate();
    }
//    emit messageRequested(QVariant(QString(tr("Welcome!"))));
}

void FKVisualInterface::showFullScreen(){
    if(_view){
        _view->showMaximized();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0) or !defined( Q_OS_MACX ))
        _view->showFullScreen();
#endif
        _view->requestActivate();
    }
}

void FKVisualInterface::hide(){
    if(_view)_view->hide();
}

FKVisualInterfaceView* FKVisualInterface::initialization(QWindow *parent){
    return new FKVisualInterfaceView(QString("FKVisualInterfaces/FKVisualInterface.qml"),parent);
}

void FKVisualInterface::showMessage(QString msg){
    emit messageRequested(FKQmlArgument(msg));
}

void FKVisualInterface::virtualKeyPressed(FKQmlArgument b, FKQmlArgument txt){
    Qt::Key key=(Qt::Key)b.toInt();
    QString text(txt.toString());
    QKeyEvent event(QKeyEvent::KeyPress,key,Qt::NoModifier,text);
    QKeyEvent event2(QKeyEvent::KeyRelease,key,Qt::NoModifier,text);
    qApp->sendEvent(_view,&event);
    qApp->sendEvent(_view,&event2);
}

void FKVisualInterface::setupContextProperties(QQmlContext* context){
    context->setContextProperty("fkvi",this);
}



